package com.songtech.base.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * json工具类
 * <br>需要导入jackson-databind-*.jar
 */
public class JsonUtil {
	/**
	 * 将传入的json字符串转换为map
	 * <br>如：
	 * <br>{
	 * <br>&nbsp;&nbsp;&nbsp;&nbsp;"id":"00001",
	 * <br>&nbsp;&nbsp;&nbsp;&nbsp;"name":"name1",
	 * <br>&nbsp;&nbsp;&nbsp;&nbsp;"list1":{
	 * <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"id":"00002",
	 * <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"name":"name2"
	 * <br>&nbsp;&nbsp;&nbsp;&nbsp;},
	 * <br>&nbsp;&nbsp;&nbsp;&nbsp;"list2":[{
	 * <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"id":"00003",
	 * <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"name":"name3"
	 * <br>&nbsp;&nbsp;&nbsp;&nbsp;}],
	 * <br>&nbsp;&nbsp;&nbsp;&nbsp;"list3":[{
	 * <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"id":"00004",
	 * <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"name":"name4"
	 * <br>&nbsp;&nbsp;&nbsp;&nbsp;},{
	 * <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"id":"00005",
	 * <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"name":"name5"
	 * <br>&nbsp;&nbsp;&nbsp;&nbsp;}]
	 * <br>}
	 * <br>map中存放的数据是：
	 * <br>key = id, value = 00001
	 * <br>key = name, value = name1
	 * <br>key = list1, value = java.util.Map
	 * <br>&nbsp;&nbsp;&nbsp;&nbsp;key = id, value = 00002
	 * <br>&nbsp;&nbsp;&nbsp;&nbsp;key = name, value = name2
	 * <br>key = list2, value = java.util.List
	 * <br>&nbsp;&nbsp;&nbsp;&nbsp;List.get(0)
	 * <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;key = id, value = 00003
	 * <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;key = name, value = name3
	 * <br>key = list3, value = java.util.List
	 * <br>&nbsp;&nbsp;&nbsp;&nbsp;List.get(0)
	 * <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;key = id, value = 00004
	 * <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;key = name, value = name4
	 * <br>&nbsp;&nbsp;&nbsp;&nbsp;List.get(1)
	 * <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;key = id, value = 00005
	 * <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;key = name, value = name5
	 * @param json json字符串
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, Object> readJsonValueToMap(String json){
		if(StringUtils.isEmpty(json)){
			return new HashMap<>();
		}
		ObjectMapper objMap = new ObjectMapper();
		Map<String, Object> map = null;
		try {
			map = objMap.readValue(json, Map.class);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(map == null){
				map = new HashMap<>();
			}
		}
		return map;
	}
}
